package com.mingtu.guards.activity;

import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.PathSmoothTool;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.view.MultiGridView;
import com.mingtu.common.view.MyDialog;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.AircraftAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.AirBaseInfoBean;
import com.mingtu.guards.bean.AirLastLocationBean;
import com.mingtu.guards.callback.MyStringDialogCallback;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;

public class AircraftMonitorActivity extends MyBaseActivity {
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.grid_view)
    MultiGridView gridView;
    @BindView(R.id.tv_aircraft_name)
    TextView tvAircraftName;
    @BindView(R.id.view_status)
    View viewStatus;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.iv_zoom)
    ImageView ivZoom;
    private List<Marker> markerList = new ArrayList<>();
    private List<Polyline> polylinesList = new ArrayList<>();
    private AMap aMap;
    private int airStatus = 0;
    private String rtmpURL;
    private String airName;
    private Timer timer = new Timer();
    private Handler mHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (!isPause) getAirBaseInfo();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private List<LatLng> latLngs = new ArrayList<>();

    /**
     * 定义并初始化定时器任务
     */
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            /**
             * 此处执行任务
             * */
            mHanlder.sendEmptyMessage(1);//通知UI更新
        }
    };
    private PathSmoothTool mpathSmoothTool;
    private Marker locationMarker;
    private boolean isPause = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_aircraft_monitor;
    }

    @Override
    protected void initView() {
        setModuleTitle("无人机监测");
        super.initView();
    }

    @Override
    protected void initData() {
        AircraftAdapter aircraftAdapter = new AircraftAdapter(context);
        gridView.setAdapter(aircraftAdapter);
        aircraftAdapter.setOnItemClickListener(new AircraftAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == 0) {//实时监测
                    if (airStatus == 0) {
                        MyDialog dialog = new MyDialog(AircraftMonitorActivity.this);
                        dialog.setMessage("无人机处于离线状态，无法查看实时监测！");
                        dialog.setOnSureClickListener(new MyDialog.OnSureClickListener() {
                            @Override
                            public void onSureClick() {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    } else {
                        //无人机直播视频
                        if (!StringUtils.isEmpty(rtmpURL)) {
                            Bundle bundle = new Bundle();
                            bundle.putString("vodeoUrl", rtmpURL);
                            bundle.putString("title", airName);
                            IntentUtils.getInstance().readyGo(AircraftMonitorActivity.this, VideoPlayActivity.class, bundle);

                        } else {
                            ToastUtils.showLong("未获取到直播链接地址~");
                        }
                    }

                } else if (position == 1) {//数据分析
                    Bundle bundle = new Bundle();
                    bundle.putString("airName", airName);
                    IntentUtils.getInstance().readyGo(AircraftMonitorActivity.this, AircraftDataAnalysisActivity.class);
                } else if (position == 2) {
                    ToastUtils.showLong("功能开发中，敬请期待！");
//                    IntentUtils.getInstance().readyGo(AircraftMonitorActivity.this, AircrafDequipmentActivity.class);
                }
            }
        });
    }

    @Override
    protected void getData() {
        initPullRefresh();
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        mpathSmoothTool = new PathSmoothTool();
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @RequiresApi(api = Build.VERSION_CODES.P)
            @Override
            public void onMapLoaded() {
                startTimer();
            }
        });
        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            LatLng location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
            locationMarker = aMap.addMarker(markerOptions);
//            markerList.add(LocationMarker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        isPause = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isPause = true;
    }

    @Override
    protected void onDestroy() {
        if (aMap != null) {
            mapView.onDestroy();
        }

        if (locationMarker != null) {
            locationMarker.remove();
        }

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        if (polylinesList.size() > 0) {
            for (Polyline polyline : polylinesList) {
                polyline.remove();
            }
            polylinesList.clear();
        }

        stopTimer();
        super.onDestroy();
    }

    /**
     * 开始循环请求
     */
    private void startTimer() {
        timer.schedule(timerTask,
                0 * 1000,//延迟0秒执行
                1500);//周期为1秒
    }

    /**
     * 结束循环请求
     */
    private void stopTimer() {

        isPause = true; //是否暂停循环请求
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }


    private void initPullRefresh() {
        srlUp.setEnableLoadMore(false);
        srlUp.setEnableRefresh(false);
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
            }
        });
    }

    /**
     * 获取无人机相关信息
     */
    private void getAirBaseInfo() {
        OkGo.<String>post(MyConstant.POST_AIR_BASEINFO)
                .tag(this)
                .upJson("")
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                AirBaseInfoBean airBaseInfoBean = new AirBaseInfoBean();
                                airBaseInfoBean = gson.fromJson(result, AirBaseInfoBean.class);

                                if (airBaseInfoBean != null) {
                                    AirBaseInfoBean.AirInfoBean airInfoBean = airBaseInfoBean.getAirInfo();
                                    if (airInfoBean != null) {
                                        airName = airInfoBean.getName();
                                        int status = airInfoBean.getStatus(); //0:离线  1:在线
                                        rtmpURL = airInfoBean.getRtmpUrl();
                                        airStatus = status;

                                        if (status == 0) { //离线的时候清除图标
                                            if (markerList.size() > 0) {
                                                for (Marker marker : markerList) {
                                                    marker.remove();
                                                }
                                                markerList.clear();
                                            }
                                        } else if (status == 1) {
                                            getAirLastLocation();
                                        }

                                        //防止页面退出了，方法还在执行，对象获取为空
                                        runOnUiThread(() -> {
                                            if (!StringUtils.isEmpty(airName) && tvAircraftName != null) {
                                                tvAircraftName.setText(airName + "");
                                            }

                                            if (viewStatus != null) {
                                                if (status == 0) {
                                                    viewStatus.setBackground(getDrawable(R.drawable.shape_circle_red));
                                                } else if (status == 1) {
                                                    viewStatus.setBackground(getDrawable(R.drawable.shape_circle_green_ff0));
                                                }
                                            }
                                        });


                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 获取无人机最新位置信息
     */
    private void getAirLastLocation() {
        OkGo.<String>post(MyConstant.POST_AIR_LAST_LOCATION)
                .tag(this)
                .upJson("")
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                AirLastLocationBean airLastLocationBean = new AirLastLocationBean();
                                airLastLocationBean = gson.fromJson(result, AirLastLocationBean.class);
                                if (airLastLocationBean != null) {
                                    AirLastLocationBean.AirInfoEntityBean airInfoEntityBean = airLastLocationBean.getAirInfoEntity();
                                    String lnglat = airInfoEntityBean.getLnglat();

                                    if (lnglat.indexOf(",") != -1) {
                                        String[] array = lnglat.split(",");
                                        if (array.length == 2) {
                                            double lng = Double.parseDouble(array[0]);
                                            double lat = Double.parseDouble(array[1]);

                                            LatLng location = new LatLng(lat, lng);

                                            if (markerList.size() > 0) {
                                                for (Marker marker : markerList) {
                                                    marker.remove();
                                                }
                                                markerList.clear();
                                            }

                                            ApplicationInfo appInfo = getApplicationInfo();
                                            ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
                                            for (int i = 1; i <= 12; i++) {
                                                int resID = getResources().getIdentifier("icon_aircraft" + i, "mipmap", appInfo.packageName);
                                                giflist.add(BitmapDescriptorFactory.fromResource(resID));
                                            }
                                            MarkerOptions markerOptions = new MarkerOptions()
                                                    .position(location)
                                                    .period(5)
                                                    .anchor(0.5f,0.5f)
                                                    .icons(giflist);
                                            Marker marker = aMap.addMarker(markerOptions);
                                            markerList.add(marker);
                                            aMap.animateCamera(CameraUpdateFactory.changeLatLng(location));

//                                            latLngs.add(location);
//                                            //去重
//                                            latLngs = new ArrayList<LatLng>(new LinkedHashSet(latLngs));
//                                            List<LatLng> optimizeLatLng = mpathSmoothTool.pathOptimize(latLngs);
//                                            Polyline mapPolyline = aMap.addPolyline(new PolylineOptions()
//                                                    .addAll(optimizeLatLng)
//                                                    .width(Constant.POLYLINE_WIDTH)
//                                                    .color(context.getResources().getColor(R.color.colorPrimary)));
//                                            polylinesList.add(mapPolyline);
                                        }
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }


    @OnClick({R.id.iv_zoom})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_zoom:
                IntentUtils.getInstance().readyGo(AircraftMonitorActivity.this, AircraftMapActivity.class);
                break;
        }
    }
}